package pannel.book;

import pannel.user.User;
import system.BasePage;

import javax.swing.*;
import java.awt.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;

public class MyBorrowedBooksPage extends BasePage {
    private BookDao bookDao;
    private JPanel booksPanel;
    private JScrollPane scrollPane;

    public MyBorrowedBooksPage(User user) {
        super(user);
        bookDao = new BookDao();
        initPageContent();
        loadBooks();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("我的借阅");
        setupContent();
    }


    private void setupContent() {
        // 使用BorderLayout来确保内容区域能够充满整个空间
        contentArea.setLayout(new BorderLayout(10, 10));

        // 添加顶部面板，包含刷新按钮
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        topPanel.setBackground(Color.WHITE);
        JButton refreshButton = new JButton("刷新列表");
        refreshButton.addActionListener(e -> loadBooks());
        topPanel.add(refreshButton);
        contentArea.add(topPanel, BorderLayout.NORTH);

        // 创建一个使用WrapLayout的面板来显示书籍卡片
        booksPanel = new JPanel(new WrapLayout(WrapLayout.LEFT, 20, 20));
        booksPanel.setBackground(Color.WHITE);

        // 创建滚动面板并设置正确的滚动策略
        scrollPane = new JScrollPane(booksPanel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 确保scrollPane能够正确显示内容
        scrollPane.setPreferredSize(new Dimension(800, 600));

        contentArea.add(scrollPane, BorderLayout.CENTER);
    }

    private void loadBooks() {
        SwingUtilities.invokeLater(() -> {
            try {
                List<Book> books = bookDao.queryUserBorrowBooks(getCurrentUser().getId());
                displayBooks(books);
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取借阅信息失败：" + e.getMessage());
            }
        });
    }

    private void displayBooks(List<Book> books) {
        // 清除现有内容
        booksPanel.removeAll();

        if (books == null || books.isEmpty()) {
            // 创建空状态面板，使用BoxLayout确保垂直居中
            JPanel emptyPanel = new JPanel();
            emptyPanel.setLayout(new BoxLayout(emptyPanel, BoxLayout.Y_AXIS));
            emptyPanel.setBackground(Color.WHITE);

            // 设置最小尺寸确保空态面板可见
            emptyPanel.setPreferredSize(new Dimension(600, 400));

            // 创建空状态图标
            JLabel iconLabel = new JLabel("📚");
            iconLabel.setFont(new Font(iconLabel.getFont().getName(), Font.PLAIN, 48));
            iconLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

            // 创建空状态文本
            JLabel textLabel = new JLabel("暂无借阅的图书");
            textLabel.setFont(new Font(textLabel.getFont().getName(), Font.PLAIN, 16));
            textLabel.setForeground(Color.GRAY);
            textLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

            // 添加组件到空状态面板
            emptyPanel.add(Box.createVerticalGlue());
            emptyPanel.add(iconLabel);
            emptyPanel.add(Box.createVerticalStrut(20));
            emptyPanel.add(textLabel);
            emptyPanel.add(Box.createVerticalGlue());

            // 将空状态面板添加到中心位置
            booksPanel.setLayout(new BorderLayout());
            booksPanel.add(emptyPanel, BorderLayout.CENTER);
        } else {
            // 如果有数据，使用WrapLayout
            booksPanel.setLayout(new WrapLayout(WrapLayout.LEFT, 20, 20));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Book book : books) {
                booksPanel.add(createBookCard(book, sdf));
            }
        }

        // 更新UI
        booksPanel.revalidate();
        booksPanel.repaint();
        scrollPane.revalidate();
        scrollPane.repaint();
    }

    private JPanel createBookCard(Book book, SimpleDateFormat sdf) {
        // 创建卡片主面板
        JPanel card = new JPanel();
        card.setLayout(new BorderLayout(15, 15));
        card.setPreferredSize(new Dimension(600, 180));
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1, true),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        card.setBackground(Color.WHITE);

        // 添加鼠标悬停效果
        card.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                card.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(70, 130, 180), 1, true),
                        BorderFactory.createEmptyBorder(15, 15, 15, 15)
                ));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                card.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(220, 220, 220), 1, true),
                        BorderFactory.createEmptyBorder(15, 15, 15, 15)
                ));
            }
        });

        // 左侧图片面板
        JPanel imagePanel = new JPanel(new BorderLayout());
        imagePanel.setPreferredSize(new Dimension(100, 140));
        imagePanel.setBackground(Color.WHITE);
        JLabel imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(JLabel.CENTER);

        if (book.getImagePath() != null && !book.getImagePath().isEmpty()) {
            ImageIcon imageIcon = new ImageIcon(book.getImagePath());
            Image image = imageIcon.getImage().getScaledInstance(100, 140, Image.SCALE_SMOOTH);
            imageLabel.setIcon(new ImageIcon(image));
        } else {
            imageLabel.setText("暂无图片");
            imageLabel.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        }
        imagePanel.add(imageLabel, BorderLayout.CENTER);

        // 右侧信息面板
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setBackground(Color.WHITE);

        // 书名
        JLabel nameLabel = new JLabel(book.getName());
        nameLabel.setFont(new Font(nameLabel.getFont().getName(), Font.BOLD, 16));
        nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 作者和出版社
        JLabel authorLabel = new JLabel("作者：" + book.getAuthor());
        JLabel publisherLabel = new JLabel("出版社：" + book.getPublisher());
        authorLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        publisherLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 借阅时间
        JLabel timeLabel = new JLabel("借阅时间：" + sdf.format(book.getBorrowTime()));
        timeLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 添加所有信息标签
        infoPanel.add(nameLabel);
        infoPanel.add(Box.createVerticalStrut(10));
        infoPanel.add(authorLabel);
        infoPanel.add(Box.createVerticalStrut(5));
        infoPanel.add(publisherLabel);
        infoPanel.add(Box.createVerticalStrut(5));
        infoPanel.add(timeLabel);
        infoPanel.add(Box.createVerticalStrut(15));

        // 归还按钮
        JButton returnButton = new JButton("归还图书");
        returnButton.setAlignmentX(Component.LEFT_ALIGNMENT);
        returnButton.addActionListener(e -> returnBook(book));
        infoPanel.add(returnButton);

        // 组装卡片
        card.add(imagePanel, BorderLayout.WEST);
        card.add(infoPanel, BorderLayout.CENTER);

        return card;
    }

    private void returnBook(Book book) {
        try {
            if (bookDao.returnBook(book.getId())) {
                JOptionPane.showMessageDialog(this, "归还成功！");
                loadBooks(); // 刷新界面
            } else {
                JOptionPane.showMessageDialog(this, "归还失败！");
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "归还失败：" + ex.getMessage());
        }
    }
}

// 自定义WrapLayout类，用于自动换行的布局管理
class WrapLayout extends FlowLayout {
    public WrapLayout() {
        super();
    }

    public WrapLayout(int align) {
        super(align);
    }

    public WrapLayout(int align, int hgap, int vgap) {
        super(align, hgap, vgap);
    }

    @Override
    public Dimension preferredLayoutSize(Container target) {
        return layoutSize(target, true);
    }

    @Override
    public Dimension minimumLayoutSize(Container target) {
        return layoutSize(target, false);
    }

    private Dimension layoutSize(Container target, boolean preferred) {
        synchronized (target.getTreeLock()) {
            int targetWidth = target.getWidth();
            if (targetWidth == 0) {
                targetWidth = Integer.MAX_VALUE;
            }

            int hgap = getHgap();
            int vgap = getVgap();
            Insets insets = target.getInsets();
            int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
            int maxWidth = targetWidth - horizontalInsetsAndGap;

            Dimension dim = new Dimension(0, 0);
            int rowWidth = 0;
            int rowHeight = 0;

            int nmembers = target.getComponentCount();
            for (int i = 0; i < nmembers; i++) {
                Component m = target.getComponent(i);
                if (m.isVisible()) {
                    Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
                    if (rowWidth + d.width > maxWidth) {
                        addRow(dim, rowWidth, rowHeight);
                        rowWidth = 0;
                        rowHeight = 0;
                    }
                    if (rowWidth != 0) {
                        rowWidth += hgap;
                    }
                    rowWidth += d.width;
                    rowHeight = Math.max(rowHeight, d.height);
                }
            }
            addRow(dim, rowWidth, rowHeight);

            dim.width += horizontalInsetsAndGap;
            dim.height += insets.top + insets.bottom + vgap * 2;

            return dim;
        }
    }

    private void addRow(Dimension dim, int rowWidth, int rowHeight) {
        dim.width = Math.max(dim.width, rowWidth);
        if (dim.height > 0) {
            dim.height += getVgap();
        }
        dim.height += rowHeight;
    }
}